<template>
  <view class="container-wrap" :style="{ height: currentHeight }">
    <view class="title">
      <view @click="isFullScreenFn">路损分析</view>
      <view class="flex">
        <view style="width: 150px">
          <uni-select
            v-model="selectValue"
            multiple
            dataKey="coalSourceType"
            dataValue="id"
            :localdata="selectList"
            @change="conditionChange"
          ></uni-select>
        </view>
        <view style="width: 60px; margin-left: 10px">
          <uni-select
            v-model="dateType"
            dataKey="name"
            dataValue="value"
            :clear="false"
            :localdata="dateTypeList"
            @change="conditionChange"
          ></uni-select>
        </view>
      </view>
    </view>
    <view class="echart-wrap">
      <echarts-uniapp
        ref="roadLossAnalysisRef"
        canvasId="roadLossAnalysisChart"
      ></echarts-uniapp>
    </view>
    <uni-loading v-show="showLoading"></uni-loading>
  </view>
</template>
<script>
import { colorList } from './baseData.js';
import {
  getRoadLossAnalysis,
  getRoadLossScreenCondition
} from '@/api/dashboard';
import { getCurrentDateForParam } from '@/utils/common.js';
import echartsUniapp from '../common/echarts-uniapp/echarts-uniapp';
import uniLoading from '../common/uni-loading/uni-loading';
export default {
  components: {
    echartsUniapp,
    uniLoading
  },
  props: {
    currentHeight: {
      type: String,
      default: '100vh'
    }
  },
  data() {
    return {
      showLoading: false,
      selectValue: [],
      selectList: [],
      dateType: 'daterange',
      dateTypeList: [
        { name: '日', value: 'daterange' },
        { name: '周', value: 'week' },
        { name: '月', value: 'month' },
        { name: '季', value: 'quarter' },
        { name: '年', value: 'year' }
      ],
      dataColorMap: {},
      cacheRankList: [],
      cacheDataInfoList: [],
      option: {
        tooltip: {
          trigger: 'axis',
          confine: true,
          responsive: true,
          axisPointer: {
            type: 'line',
            axis: 'auto',
            snap: true
          },
          textStyle: {
            testShadowColor: 'transparent',
            textShadowBlur: 10
          },
          padding: 5
        },
        legend: {
          top: 6,
          data: []
        },
        grid: {
          left: 10,
          right: 10,
          top: 20,
          bottom: 0,
          containLabel: true
        },
        xAxis: {
          type: 'value',
          min: -0.3,
          max: 0.3,
          axisLabel: {
            formatter: (value) => {
              if ([-0.3, 0.3].includes(value)) {
                return '';
              }
              return value;
            }
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false
          },
          data: []
        },
        yAxis: {
          type: 'value',
          min: 0,
          minInterval: 1,
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed'
            }
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: true,
            onZero: false
          },
          axisLabel: {
            formatter: '{value}车'
          }
        },
        series: []
      }
    };
  },
  async mounted() {
    await this.getRoadLossScreenConditionFn();
    this.getRoadLossAnalysisFn();
  },
  methods: {
    isFullScreenFn() {
      if (this.currentHeight === '100vh') {
        return;
      }
      this.$tab.navigateTo('/packageA/pages/dashboard/roadLossAnalysis');
    },
    conditionChange() {
      this.getRoadLossAnalysisFn();
    },
    async getRoadLossScreenConditionFn() {
      const res = await getRoadLossScreenCondition();
      if (res.code === 0) {
        const result = res.data || [];
        this.selectList = [
          ...result.map((e) => {
            e.id = `${e.productId}${e.coalSourceId}`;
            return e;
          }),
          { id: 'ALL', coalSourceType: '总煤源/总煤种' }
        ];
      }
    },
    async getRoadLossAnalysisFn() {
      const data = {
        dateType: this.dateType,
        conditionReqVOS: this.getConditionReqVOS(),
        totalReqVOS: this.getTotalReqVOS(),
        time: getCurrentDateForParam(new Date())
      };
      this.showLoading = true;
      const res = await getRoadLossAnalysis(data);
      if (res.code === 0) {
        this.option.yAxis.max = this.isHasData(res?.data?.dataInfoList || [])
          ? 1
          : null;
        this.option.tooltip.formatter = this.getTooltip();
        this.cacheDataInfoList = res?.data?.dataInfoList || [];
        this.cacheRankList = res?.data?.rangeRespVOS || [];
        this.option.series = this.getSeriesList(res?.data?.dataInfoList || []);
        this.$refs.roadLossAnalysisRef.initChart(this.option);
        this.showLoading = false;
      }
    },
    isHasData(list) {
      return list.every(
        (e) =>
          !e?.roadLossDataValues?.length && !e?.correctRoadLossCenterVOS?.length
      );
    },
    getTooltip() {
      return (param) => {
        const x = param[0].value[0];
        const rankData = this.cacheRankList.find(
          (e) => e.min <= x && e.max >= x
        );
        const rangeLabel = rankData.rangeLabel;
        const roadLossLst = rankData.roadLossDataRespVOS || [];
        const scatterLst = param.filter((e) => e.seriesType === 'scatter');
        const roadLossList = param
          .filter((e) => e.seriesType === 'line')
          .map((m) => {
            const data = roadLossLst.find(
              (o) => o.coalSourceTypeId === m.seriesName
            );
            m.coalSourceType = data.coalSourceType;
            m.carNumberStr = data.carNumberStr;
            m.shortfallWeight = data.shortfallWeight;
            m.percentValue = data.percentValue;
            return m;
          });
        const scatterList = scatterLst.map((e) => {
          e.value = this.cacheDataInfoList.find(
            (m) => m.coalSourceTypeId === e.name
          )?.roadLossCenterVOS;
          e.percentValue = this.cacheDataInfoList.find(
            (m) => m.coalSourceTypeId === e.name
          )?.percentValue;
          return e;
        });
        let result = `${rangeLabel}\n\r`;
        if (!roadLossList.length) {
          scatterList.forEach((e, v) => {
            if (v === scatterList.length - 1) {
              result += `${e.marker} 平均损耗: ${e.value?.[1]}车 ${e.value?.[0]}`;
            } else {
              result += `${e.marker} 平均损耗: ${e.value?.[1]}车 ${e.value?.[0]}\n\r`;
            }
          });
        } else {
          scatterList.forEach((e, v) => {
            result += `${e.marker} 平均损耗: ${e.value?.[1]}车 ${e.value?.[0]}\n\r`;
          });
          roadLossList.forEach((e, v) => {
            if (v === roadLossList.length - 1) {
              result += `${e.marker} ${e.coalSourceType}: ${e.carNumberStr}车 ${
                e.shortfallWeight
              } ${e.percentValue || 0}%`;
            } else {
              result += `${e.marker} ${e.coalSourceType}: ${e.carNumberStr}车 ${
                e.shortfallWeight
              } ${e.percentValue || 0}%\n\r`;
            }
          });
        }
        return result;
      };
    },
    getSeriesList(list) {
      const result = list.map((e, v) => {
        this.dataColorMap[e.coalSourceTypeId] = colorList[v];
        return {
          name: e.coalSourceTypeId,
          type: 'line',
          smooth: true,
          symbolSize: 5,
          data: e.roadLossDataValues,
          itemStyle: {
            normal: {
              color: colorList[v],
              borderColor: colorList[v],
              borderWidth: 2
            }
          },
          lineStyle: {
            color: colorList[v]
          }
        };
      });
      return [
        ...result,
        {
          symbol: 'triangle',
          symbolRotate: 180,
          symbolSize: 10,
          data: this.getPointerList(list),
          type: 'scatter'
        }
      ];
    },
    getPointerList(list) {
      return list.map((e, v) => {
        return {
          name: e.coalSourceTypeId,
          value: e.correctRoadLossCenterVOS || [],
          itemStyle: {
            color: colorList[v]
          }
        };
      });
    },
    getConditionReqVOS() {
      if (!this.selectValue.length) {
        return this.selectList
          .filter((e) => e.id !== 'ALL')
          .map((m) => {
            return this.combParams(m);
          });
      }
      return this.selectList
        .filter((e) => this.selectValue.includes(e.id) && e.id !== 'ALL')
        .map((m) => {
          return this.combParams(m);
        });
    },
    getTotalReqVOS() {
      if (this.selectValue.length === 0 || this.selectValue.includes('ALL')) {
        return this.selectList
          .filter((e) => e.id !== 'ALL')
          .map((m) => {
            return this.combParams(m);
          });
      }
    },
    combParams(m) {
      return {
        productId: m.productId,
        productName: m.productName,
        coalSourceId: m.coalSourceId,
        coalSourceName: m.coalSourceName
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.container-wrap {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 15px 10px;
  background-color: #ffffff;
  border-radius: 8px;
  .title {
    display: flex;
    font-size: 14px;
    color: #000000;
    font-weight: 600;
    padding-bottom: 11px;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #e6e6e6;
  }
  .echart-wrap {
    flex: 1;
  }
  .flex {
    display: flex;
  }
  .flex-direction {
    flex-direction: column;
  }
}
</style>
